from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from .models import Reader
from .serializer import ReaderSerializer
import jwt,datetime

class ReaderLogin(APIView):
    def post(self, request):
        name = request.data.get('name')
        password = request.data.get('password')

        if not all([name, password]):
            return Response({'error':'不能输入为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            reader = Reader.objects.get(name=name)
        except Reader.DoesNotExist:
            return Response({'error':'用户不存在'}, status=status.HTTP_400_BAD_REQUEST)

        if password!=reader.password:
            return Response({'error':'密码输入错误'}, status=status.HTTP_400_BAD_REQUEST)

        token=jwt.encode({
            'name': name,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
        }, settings.SECRET_KEY, algorithm='HS256')

        return Response({'succeed': '登录成功','token':token}, status=status.HTTP_200_OK)


